package com.zgg.myjwt.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.zgg.myjwt.annotation.CheckToken;
import com.zgg.myjwt.annotation.LoginToken;
import com.zgg.myjwt.pojo.SysUser;
import com.zgg.myjwt.untils.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ant_Zhou
 * @email 1641583112@qq.com
 * @create 2020-05-15 22:27
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    /**
     * 拦截
     * @param httpServletRequest
     * @param httpServletResponse
     * @param object
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {

        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //查看是否是登录请求
        //检查是否有LoginToken注释，有则跳过认证
        if (method.isAnnotationPresent(LoginToken.class)) {
            LoginToken loginToken = method.getAnnotation(LoginToken.class);
            if (loginToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(CheckToken.class)) {
            CheckToken checkToken = method.getAnnotation(CheckToken.class);
            //查看请求的方法是否有检查令牌的注解 有则验证
            if (checkToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token，请重新登录");
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getClaim("id").asString();
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("访问异常！");
                }
                //用户是否存在的验证
                /** SysUser user = userService.findUserById(userId);
                 if (user == null) {
                 throw new RuntimeException("用户不存在，请重新登录");
                 }*/
                if (StringUtils.equals("2", userId)) {
                    throw new RuntimeException("用户不存在，请重新登录");
                }
                    SysUser user = new SysUser();
                    user.setAccount("111");
                    user.setPassword("abc");
                    user.setUserId((long) 2);
                    Boolean verify = JwtUtil.isVerify(token, user);
                    if (!verify) {
                        throw new RuntimeException("非法访问！");
                    }
                    return true;
                }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
